import {OpsAuth, TopicFactory} from "./TopicFactory";
import PushPacket from "./tp/WebsocketTp";

export default class WebSocketClient {
  constructor() {
    this.topicFactory = new TopicFactory();
    this.topicFactory.init();
    this.responseFutureMap = {};
  }

  close() {
    console.log("关闭webSocket 连接");
    mqClient.disConnect();
  }

  setDataListener(dataListener) {
    this.dataListener = dataListener;
  }

  connect = () => {

    let that = this;
    this.socketTask = uni.connectSocket({
      // url: 'ws://'+this.addr+'/mqtt',
	  url: 'wss://jlw.nbmicrostone.com/mqtt',
	  // url: 'ws://118.31.184.191:1887/mqtt',
      success: () => {
        console.log("连接mqtt成功");
      },
      fail: () => {
        console.log("连接mqtt失败");
      }
    });

    this.socketTask.onOpen( function (event) {
      console.log('WebSocket connection is open');

      // Send a message to the server
      let packet = new PushPacket().register(that.username, that.password);
      // console.log("send", packet.toJson())
      that.sendSocketMessage(packet.toJson())
    });

    this.socketTask.onError( function (event) {
      console.log('WebSocket connection is error', event);
    })

    this.socketTask.onMessage( function (event) {
		// console.log(event);
      // console.log('Message from server:', event.data);
      let pushPacket = JSON.parse(event.data);
      that.handleMsg(pushPacket);
    });

    this.socketTask.onClose(function (res) {
      console.log('WebSocket 已关闭！');
      !!that.dataListener && that.dataListener.onClose();
    });

  }

  // 关闭WebSocket连接
  close() {
    uni.closeSocket();
  }

  sendSocketMessage(msg) {
    this.socketTask.send({
      data: msg
    });
  }

  subscribe = (topics) => {

    let packet = new PushPacket().subscribe("USR", topics);
    // console.log("send", packet.toJson())
    this.sendSocketMessage(packet.toJson())

  }

  ping = () => {
    let packet = new PushPacket().ping("USR");
    // console.log("send", packet.toJson())
    this.sendSocketMessage(packet.toJson())
  }

  push = (qos, topic, msg) => {
    let packet = new PushPacket().push("USR", topic, msg);
    // console.log("send", packet.toJson())
    this.sendSocketMessage(packet.toJson())
  }

  send(request, listener) {
    try {
      let topic = request.topic;
      // console.log("send", request.mWrapperRequest);
      let msg = JSON.stringify(request.mWrapperRequest);
      // console.log(`发送数据\ntopic:${topic}\nmsg:${msg}`);

      let push = this.push(0, topic, msg);
      return push;
    } catch (e) {
      console.error(e, "发送mqtt数据失败");
    }

    return false;
  }

  sendResponse(response) {
    try {
      let topic = response.topic;
      let msg = JSON.stringify(response.mResponse);
      console.log(`发送数据\ntopic:${topic}\nmsg:${msg}`);

      let push = this.push(0, topic, msg);
      return push;
    } catch (e) {
      console.error(e, "发送mqtt数据失败");
    }

    return false;
  }

  handleMsg = (packet) => {
    try {

      const {header, body} = packet;
      const {topic, msg} = body;
      switch (header.packetType) {
        case "Reg_ACK":
          console.log("注册回复:", body.responseCode);
          !!this.dataListener && this.dataListener.onConnect(body.responseCode == "CONNECTION_ACCEPTED");
          break;
        case "PUBLISH":
          this.headlePush(topic, msg);
          break;
        case "SUB_ACK":
          !!this.dataListener && this.dataListener.onSubAck(true);
          break;
        case "PUBLISH_ACK":
          !!this.dataListener && this.dataListener.onPushAck(true);
          break;
      }


    } catch (e) {
      console.error("处理mqtt收到的数据异常", e);
    }
  }

  headlePush = (topic, msg) => {
    // console.log(`收到消息:${topic}, ${msg}`);
	// console.log(topic);
	// console.log(msg);
	// topic='/sys/q21crvVHypW/naodian1/thing/event/property/post'
 //    msg={'productKey': 'q21crvVHypW', 'deviceName': 'naodian1', 'version': '1.0', 'id': '602741957', 'method': 'thing.service.property.post', 'params': {'OUT': {'value': [3.2188033098963587, 1.7056499899623487, 0.8938531798750771, 0.061882366777449786, 0.01636000721146087, 0.024307907770677036, 0.0035965383653351526], 'time': 1729156368672, 'type': 'string'}}}
 //    msg={"productKey":"q21crvVHypW","deviceName":"naodian1","version":"1.0","id":"542060242","method":"thing.service.property.post","params":{"OUT":{"value":"[3.2188033098963587, 1.7056499899623487, 0.8938531798750771, 0.061882366777449786, 0.01636000721146087, 0.024307907770677036, 0.0035965383653351526]","time":1729157127063,"type":"string"}}}
	// // Call dataListener.onHandle method (assuming dataListener is defined elsewhere)
    !!this.dataListener && this.dataListener.onHandle(topic, msg);

    // Retrieve topic info from topicFactory
    let topicInfo = this.topicFactory.findThingTopic(topic);
    if (topicInfo) {
      // console.log("物模型信息")
	  msg=msg.replace(/'/g, '"');
      let jsonObject = JSON.parse(msg);
      let fun = topicInfo.fun;
      let opAuth = topicInfo.opAuth;

      let response = null;
      let id = null;
		// console.log(opAuth);
      switch (fun) {
        case 'PropertyPost':
          if (opAuth === 'PUSH') {
            let payload = JSON.parse(msg);
            let params = jsonObject.params;
            payload.params = (params);
            response = payload;
            id = payload.id;
            !!this.dataListener && this.dataListener.onRequestSuccess(topic, payload);
          } else if (opAuth === 'SUB') {
            let payload = JSON.parse(msg);
            response = payload;
            id = payload.id;
            !!this.dataListener && this.dataListener.onResponseSuccess(topic, payload);
          }
          break;
        case 'PropertySet':
          if (opAuth === 'SUB') {
            let payload = JSON.parse(msg);
            let params = jsonObject.params;
            payload.params = (params);
            response = payload;
            id = payload.id;
            !!this.dataListener && this.dataListener.onRequestSuccess(topic, payload);
          } else if (opAuth === 'PUSH') {
            let payload = JSON.parse(msg);
            response = payload;
            id = payload.id;
            !!this.dataListener && this.dataListener.onResponseSuccess(topic, payload);
          }
          break;
        case 'EventPost':
          if (opAuth === 'PUSH') {
            let payload = JSON.parse(msg);
            let params = jsonObject.params;
            payload.params = (params);
            response = payload;
            id = payload.id;
            !!this.dataListener && this.dataListener.onRequestSuccess(topic, payload);
          } else if (opAuth === 'SUB') {
            let payload = JSON.parse(msg);
            response = payload;
            id = payload.id;
            !!this.dataListener && this.dataListener.onResponseSuccess(topic, payload);
          }
          break;
        case 'Service':
          if (opAuth === 'SUB') {
            let payload = JSON.parse(msg);
            response = payload;
            id = payload.id;
            !!this.dataListener && this.dataListener.onRequestSuccess(topic, payload);
          } else if (opAuth === 'PUSH') {
            let payload = JSON.parse(msg);
            let params = jsonObject.data;
            if (params) {
              payload.setData(params);
            }
            response = payload;
            id = payload.id;
            !!this.dataListener && this.dataListener.onResponseSuccess(topic, payload);
          }
          break;
      }

      if (id && response) {
        let responseFuture = this.responseFutureMap[id];
        if (responseFuture) {
          responseFuture.getListener().onSuccess(topic, response);
          delete this.responseFutureMap[id];
        }
      }
    }else{
      topicInfo = this.topicFactory.findBasicTopic(topic);
      if(topicInfo){
        console.log("这是基础信息");
        let jsonObject = JSON.parse(msg);
        let fun = topicInfo.fun;
        let opAuth = topicInfo.opAuth;

        let response = null;
        let id = null;

        switch (fun) {
          case "OTA_UPGRADE":
            console.log("固件升级信息", fun,  opAuth);
            if (opAuth == (OpsAuth.PUSH)) {
              // 设备上报固件升级信息
              let payload = JSON.parse(msg);
              !!this.dataListener && this.dataListener.onOTA(topic, payload);
            }
            break;
        }
      }
    }
  }

}


